<!--角色的管理页面：对角色的增删改查-->

<template>
  <!--查询、新增、修改、删除角色-->
  <div class="app-container">
    <div class="filter-container" style="display: flex; margin: 0 auto; justify-content: space-between;">
      <div>
        <el-input
          v-model.trim="queryParams.code"
          placeholder="角色编码"
          clearable
          style="width: 160px;"
          class="filter-item split-item"
        />
        <el-input
          v-model.trim="queryParams.name"
          placeholder="角色名称"
          clearable
          style="width: 160px;"
          class="filter-item split-item"
        />
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          plain
          @click="handleFilter"
        >查询</el-button>
        <el-button
          v-waves
          class="filter-item"
          plain
          icon="el-icon-refresh"
          @click="resetQueryParams"
        >重置
        </el-button>
      </div>
      <div style="margin-right: 50px;">
        <el-button
          v-permission="['iam:role:create']"
          v-waves
          class="filter-item"
          plain
          size="mini"
          @click="onCreateItem"
        >新增
        </el-button>
        <el-button
          v-permission="['iam:role:edit']"
          v-waves
          class="filter-item"
          plain
          size="mini"
          :disabled="itemTableSelectedCount !== 1"
          @click="onEditItem"
        >修改
        </el-button>
        <el-button
          v-permission="['iam:role:delete']"
          v-waves
          class="filter-item"
          plain
          size="mini"
          :disabled="itemTableSelectedCount <= 0"
          @click="onRemoveItem"
        >删除
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      ref="itemTable"
      v-loading="itemListLoading"
      v-el-height-adaptive-table="{bottomOffset: 70}"
      row-key="id"
      :data="itemList"
      border
      fit
      highlight-current-row
      class="item-table"
      height="100px"
      :cell-style="{padding:'5px'}"
      :header-cell-style="{padding:'5px'}"
      @selection-change="onItemTableSelectionChange"
      @row-dblclick="onItemRowClick"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        prop="code"
        header-align="center"
        width="240"
        label="编码"
      />
      <el-table-column
        prop="name"
        header-align="center"
        width="240"
        label="名称"
      />
      <el-table-column
        prop="sortNo"
        header-align="center"
        width="100"
        label="排序"
      />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-link type="primary" :underline="false" style="margin-right: 10px; font-size: 12px;" @click.stop="onFuncGrant(row)">功能授权
          </el-link>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      :total="queryParams.total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="loadItemList"
    />

    <!-- edit-drawer -->
    <el-drawer
      ref="editDrawer"
      :title="dataForm.id ? '编辑' : '新增'"
      :visible.sync="showEditDrawer"
      direction="rtl"
      custom-class="edit-drawer"
      size="50%"
      :close-on-press-escape="drawerCloseOnEsc"
      :wrapper-closable="drawerWrapperClosable"
    >
      <div class="edit-drawer-content">
        <el-form ref="dataForm" :model="dataForm" :rules="dataFormRule" label-width="80px">
          <el-row :gutter="23">
            <el-col :span="23">
              <el-form-item label="角色编码" prop="code">
                <el-input v-model.trim="dataForm.code" placeholder="请输入角色编码" :disabled="dataForm.id !== undefined" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="23">
            <el-col :span="23">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model.trim="dataForm.name" placeholder="请输入角色名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="23">
            <el-col :span="23">
              <el-form-item label="角色排序" prop="sortNo">
                <el-input-number v-model.trim="dataForm.sortNo" placeholder="请输入角色排序" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="edit-drawer-footer">
        <el-button
          v-waves
          class="filter-item"
          plain
          size="mini"
          @click="showEditDrawer = false"
        >取消
        </el-button>

        <el-button
          v-waves
          class="filter-item"
          size="mini"
          type="primary"
          @click="onSaveData"
        >保存
        </el-button>
      </div>
    </el-drawer>

    <!-- 功能授权抽屉 -->
    <el-drawer
      ref="grantDrawer"
      :title="dataForm.name+'-['+dataForm.code+'] ' + '功能授权'"
      :visible.sync="showMenuGrantDrawer"
      direction="rtl"
      custom-class="edit-drawer"
      size="75%"
      :close-on-press-escape="drawerCloseOnEsc"
      :wrapper-closable="drawerWrapperClosable"
    >
      <div class="edit-drawer-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="flex flex-direction w-100">
              <div class="flex justify-center align-center" style="height: 24px">WEB端菜单</div>
              <div class="menu-container" style="border: 1px #aaa solid; border-radius: 4px">
                <el-tree
                  ref="webMenuTree"
                  :data="webMenuTreeList"
                  :props="{label: 'name', children: 'children'}"
                  node-key="id"
                  :default-expand-all="true"
                  show-checkbox
                />
              </div>
            </div>
          </el-col>
        <!--  <el-col :span="12">
            <div class="flex flex-direction  w-100">
              <div class="flex justify-center align-center" style="height: 24px">移动端菜单</div>
              <div class="menu-container" style="border: 1px #aaa solid; border-radius: 4px">
                <el-tree
                  ref="appMenuTree"
                  :data="appMenuTreeList"
                  :props="{label: 'name', children: 'children'}"
                  node-key="id"
                  :default-expand-all="true"
                  show-checkbox
                />
              </div>
            </div>
          </el-col>-->
        </el-row>
      </div>
      <div class="edit-drawer-footer">
        <el-button
          v-waves
          class="filter-item"
          plain
          size="mini"
          @click="showMenuGrantDrawer = false"
        >取消
        </el-button>

        <el-button
          v-waves
          class="filter-item"
          size="mini"
          type="primary"
          @click="onSaveFuncGrantData"
        >保存
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js'
import waves from '@/directive/waves'
import elHeightAdaptiveTable from '@/directive/el-table'
import Pagination from '@components/Pagination'

import { treeDataTranslate, resetObject, fillObject } from '@utils/index'

import Settings from '@/settings'

import RoleApi from '@api/iam/role'
import webMenuApi from '@api/iam/webMenu'
import appMenuApi from '@api/iam/appMenu'

let self

export default {
  name: 'IamRoleList',
  components: { Pagination },
  directives: { permission, waves, elHeightAdaptiveTable },
  data() {
    return {
      itemList: [],
      itemListLoading: false,
      itemTableSelectedCount: 0,
      showEditDrawer: false,
      showMenuGrantDrawer: false,
      drawerCloseOnEsc: Settings.drawerCloseOnEsc,
      drawerWrapperClosable: Settings.drawerWrapperClosable,
      //appMenuTreeList: [],
      webMenuTreeList: [],
      currentSelectRole: undefined,
      dataForm: {
        id: undefined,
        code: undefined,
        name: undefined,
        sortNo: undefined
      },
      queryParams: {
        code: undefined,
        name: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dataFormRule: {
        code: [
          { required: true, message: '请输入角色编码', trigger: 'blur' },
          { min: 1, max: 30, message: '编码长度在1到30个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 20, message: '配置名称长度在1到20个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  created() {
    self = this
    self.loadDependParams()
    this.loadItemList()
  },
  methods: {
    loadDependParams() {
    },
    resetQueryParams() {
      resetObject(this.queryParams, undefined, ['pageNum', 'pageSize', 'total'])
      this.handleFilter()
    },
    handleFilter() {
      this.queryParams.pageNum = 1
      this.loadItemList()
    },
    loadItemList() {
      this.itemListLoading = true

      if (this.$refs.itemTable) {
        this.$refs.itemTable.clearSelection()
      }

      RoleApi.fetchList(this.queryParams).then(response => {
        const { page } = response.data
        this.itemList.splice(0, this.itemList.length, ...page.records)
        this.queryParams.total = page.total
      }).finally(() => {
        this.itemListLoading = false
      })
    },
    onCreateItem() {
      this.openEditDrawer(null)
    },
    onEditItem() {
      if (!this.$refs.itemTable) {
        return
      } else if (this.$refs.itemTable.selection.length !== 1) {
        return
      }
      const item = this.$refs.itemTable.selection[0]
      this.openEditDrawer(item)
    },
    onItemTableSelectionChange(items) {
      this.itemTableSelectedCount = items.length
    },
    onItemRowClick(item) {
      if (this.$appConfig && !this.$appConfig.rowClickEdit) {
        return
      }
      this.openEditDrawer(item)
    },
    openEditDrawer(item) {
      if (item) {
        fillObject(this.dataForm, item)
        this.dataForm.type = item.type.value
      } else {
        resetObject(this.dataForm)
      }

      this.showEditDrawer = true
    },
    onSaveData() {
      const dataForm = this.$refs.dataForm
      dataForm.validate((valid) => {
        if (!valid) {
          return
        }
        this.doSaveData()
      })
    },
    doSaveData() {
      RoleApi.save(this.dataForm).then(() => {
        this.showEditDrawer = false
        resetObject(this.dataForm)
        this.loadItemList()
      })
    },
    onRemoveItem() {
      if (!this.$refs.itemTable) {
        return
      } else if (this.$refs.itemTable.selection.length <= 0) {
        return
      }

      const items = this.$refs.itemTable.selection
      const ids = items.map((item) => item.id)
      this.$confirm('确定删除所选角色', '提示').then(() => {
        this.doRemoveItem(ids)
      })
    },
    doRemoveItem(ids) {
      RoleApi.remove(ids).then(() => {
        this.loadItemList()
      })
    },
    // 授权时加载全部菜单 并勾选授权的菜单
    async onFuncGrant(item) {
      fillObject(this.dataForm, item)
      await this.loadMenuList()
    },
    // 加载全部菜单列表
    async loadMenuList() {
      if (this.webMenuTreeList.length <= 0) {
        await webMenuApi.fetchList({ includeSelf: false, includeRoot: false }).then(response => {
          const list = treeDataTranslate(response.data.list)
          this.webMenuTreeList.splice(0, this.webMenuTreeList.length, ...list)
        })
      }

      /*if (this.appMenuTreeList.length <= 0) {
        await appMenuApi.fetchList({ includeSelf: false, includeRoot: false }).then(response => {
          const list = treeDataTranslate(response.data.list)
          this.appMenuTreeList.splice(0, this.appMenuTreeList.length, ...list)
        })
      }*/
      this.loadRoleMenu()
    },
    // 加载角色对应的菜单
    loadRoleMenu() {
      if (!this.dataForm.id) {
        return
      }

      RoleApi.fetchRoleMenu(this.dataForm.id).then(response => {
        const { appMenus, webMenus } = response.data
        const appMenuIds = appMenus.map((item) => item.id)
        const webMenuIds = webMenus.map((item) => item.id)
        this.showMenuGrantDrawer = true
        this.$nextTick(() => {
          if (this.$refs.appMenuTree) {
            this.$refs.appMenuTree.setCheckedKeys(appMenuIds)
          }

          if (this.$refs.webMenuTree) {
            this.$refs.webMenuTree.setCheckedKeys(webMenuIds)
          }
        })
      })
    },
    // 保存 给角色分配菜单权限
    onSaveFuncGrantData() {
      const appMenuIds = this.$refs.appMenuTree.getCheckedKeys()
      const webMenuIds = this.$refs.webMenuTree.getCheckedKeys()
      RoleApi.grantRoleMenu(this.dataForm.id, appMenuIds, webMenuIds).then(response => {
        resetObject(this.dataForm)
        this.$refs.webMenuTree.setCheckedKeys([])
        this.$refs.appMenuTree.setCheckedKeys([])
        this.showMenuGrantDrawer = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .menu-container {
    max-height: calc(100vh - 160px);
    height: calc(100vh - 160px);
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>
